import os
import re
import sys
import getopt

n = -1
file = "0"
dir_down = "0"
dir_this = "0"
stop = "0"
Stop = {}


def readStop(stop):
    f = open(stop, "r", encoding="utf-8")
    for line in f:
        if line == "\n":
            continue
        else:
            line = line.split("\n")[0]
            rep = re.compile(r"([A-Z]|[a-z])\w+|([A-Z]|[a-z])")
            words = re.finditer(rep, line)
            for word in words:
                Stop[word.group(0)] = 1
    # print(Stop)


# 进行单个读取统计
def wordStatis(file):
    Word_all = {}
    result = {}  # 最终的结果
    middle = {}  # 中间临时排序统计

    # 处理文件
    def process(file):
        f = open(file, "r", encoding="utf-8")
        for line in f:
            if line == "\n":
                continue
            else:
                line = line.split("\n")[0]
                rep = re.compile(r"([A-Z]|[a-z])\w+|([A-Z]|[a-z])")
                words = re.finditer(rep, line)
                for word in words:
                    Statistics(word.group(0).lower())

    # 进行统计单词
    def Statistics(word):
        if word not in Stop:
            if word in Word_all:
                Word_all[word]["number"] = Word_all[word]["number"] + 1
            else:
                Word_all[word] = {}
                Word_all[word]["number"] = 1

    # 进行排序
    def sortWord(wordall):
        y1 = {k: v for k, v in sorted(wordall.items(), key=lambda item: item[1]["number"], reverse=True)}
        base_char = next(iter(y1))
        number = y1[base_char]["number"]
        # print(number)
        for item in y1:
            # 相等的话就进行插入
            if y1[item]["number"] == number:
                middle[item] = {}
                middle[item]["number"] = y1[item]["number"]
            # 不相等的话就进行排序后进行插入
            else:
                # 对出现次数相同的单词进行排序，按照字典序的大小进行排序
                y2 = {k: v for k, v in sorted(middle.items(), key=lambda item: item[0])}
                result.update(y2)
                middle[item] = {}
                middle[item]["number"] = y1[item]["number"]
                number = y1[item]["number"]
        y2 = {k: v for k, v in sorted(middle.items(), key=lambda item: item[0])}
        result.update(y2)

    def Calc():
        numberAll = 0.00
        for word in result:
            numberAll = numberAll + result[word]["number"]
        for word in result:
            result[word]["p"] = float(result[word]["number"] * 100.00 / numberAll)
        # print("test: ")
        # print(numberAll)

    def printResult(result):
        if n == -1:
            for item in result:
                if len(item) >= 8:
                    print(item + "\t" + str(result[item]["number"]) + "\t" + "{:.2f}".format(result[item]["p"]) + "%")
                else:
                    print(item + "\t\t" + str(result[item]["number"]) + "\t" + "{:.2f}".format(result[item]["p"]) + "%")
        else:
            begin = 0
            for item in result:
                if begin < n:
                    # print(begin)
                    if len(item) >= 8:
                        print(
                            item + "\t" + str(result[item]["number"]) + "\t" + "{:.2f}".format(result[item]["p"]) + "%")
                    else:
                        print(item + "\t\t" + str(result[item]["number"]) + "\t" + "{:.2f}".format(
                            result[item]["p"]) + "%")
                    begin = begin + 1
                else:
                    break

    process(file)
    sortWord(Word_all)
    Calc()
    printResult(result)
    # print(result)


# 遍历文件夹目录
def list_allFile(path, all_files=[]):
    if os.path.exists(path):
        files = os.listdir(path)
        for file in files:
            if os.path.isdir(os.path.join(path, file)):
                list_allFile(os.path.join(path, file), all_files)
            else:
                all_files.append(os.path.join(path, file))
    else:
        print('this path not exist')
    return all_files


# 遍历所有文件
def allFile(path):
    all_files = list_allFile(path)
    for file in all_files:
        print(file)
        wordStatis(file)


# 当前文件夹
def nowFile(path, all_files=[]):
    if os.path.exists(path):
        files = os.listdir(path)
    else:
        print('this path not exist')
    for file in files:
        if os.path.isdir(os.path.join(path, file)):
            continue
        else:
            all_files.append(os.path.join(path, file))
    for file in all_files:
        print(file)
        wordStatis(file)


def main(argv):
    global n, file, dir_down, dir_this, stop
    try:
        opts, args = getopt.getopt(sys.argv[1:], '-s: -d: -f: -n: -x:')
    except getopt.GetoptError:
        print("输入有误")
        sys.exit(2)
    for opt, arg in opts:
        if opt == "-n":
            n = int(arg)
            # print("输出前 " + n + "位")
        elif opt == "-f":
            file = arg
            print('输入的文件为: ', file)

        elif opt == "-s":
            dir_down = arg
            print("遍历目录为:", dir_down)

        elif opt == "-d":
            dir_this = arg
            print('输入目录为:', dir_this)

        elif opt == "-x":
            stop = arg
            print("停止目录为:", stop)


if __name__ == "__main__":
    main(sys.argv[1:])
    if stop != "0":
        readStop(stop)
    if file != "0":
        wordStatis(file)
    if dir_down != "0":
        allFile(dir_down)
    if dir_this != "0":
        nowFile(dir_this)
